package com.supplychain.financial.parent.common.emchat;

import com.supplychain.financial.parent.common.emchat.api.ChatGroupAPI;
import com.supplychain.financial.parent.common.emchat.api.SendMessageAPI;
import com.supplychain.financial.parent.common.emchat.comm.EasemobRestAPIFactory;
import com.supplychain.financial.parent.common.emchat.comm.body.*;
import com.supplychain.financial.parent.common.emchat.api.ChatMessageAPI;
import com.supplychain.financial.parent.common.emchat.api.IMUserAPI;
import com.supplychain.financial.parent.common.emchat.comm.ClientContext;
import com.supplychain.financial.parent.common.emchat.comm.wrapper.BodyWrapper;
import com.supplychain.financial.parent.common.emchat.comm.wrapper.ResponseWrapper;
import com.supplychain.financial.parent.common.util.StringUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;

import java.util.Map;


public class Emchat {
	private static IMUserAPI userService;
	private static ChatMessageAPI recordService;
	private static SendMessageAPI chatService;
	private static ChatGroupAPI chatGroup;
	private static Logger log = Logger.getLogger(Emchat.class);
	
	private static long GROUP_MAX_USER = 200;

	static{
		EasemobRestAPIFactory factory = ClientContext.getInstance().init(ClientContext.INIT_FROM_PROPERTIES).getAPIFactory();
		userService = (IMUserAPI)factory.newInstance(EasemobRestAPIFactory.USER_CLASS);
		recordService = (ChatMessageAPI)factory.newInstance(EasemobRestAPIFactory.MESSAGE_CLASS);
		chatService = (SendMessageAPI)factory.newInstance(EasemobRestAPIFactory.SEND_MESSAGE_CLASS);
		chatGroup = (ChatGroupAPI)factory.newInstance(EasemobRestAPIFactory.CHATGROUP_CLASS);
	}
	
	public static void activateEmchat(String userId,String password,String nickName)  throws RuntimeException{
		BodyWrapper userBody = new IMUserBody(userId, password, nickName);
		Object result = userService.createNewIMUserSingle(userBody);
		
		log.info(result.toString());
		if(result.toString().contains("error") && !result.toString().contains("duplicate_unique_property_exists")){
			throw new RuntimeException("聊天注册失败");
		}
	}
	
	/**
	 * 发送文本信息
	 * @param action
	 * @param userId
	 * @param extras
	 * @return
	 * @throws Exception
	 */
	public static String sendTextMessage(String sendUserId,String content, String receiveUserId,Map<String, String> extras) throws RuntimeException{
		TextMessageBody textMessage = new TextMessageBody("users",new String[]{receiveUserId},sendUserId,extras,content);
		Object result = chatService.sendMessage(textMessage);
		log.info(result.toString());
		if(result.toString().contains("error")){
			
			throw new RuntimeException("聊天发送失败");
		}
		
		return "ok";
	} 
	
	/**
	 * 批量给多个人发送文本信息
	 * @param sendUserId
	 * @param content
	 * @param receiveUsers 数组长度建议不大于20
	 * @param extras
	 * @return
	 * @throws RuntimeException
	 */
	public static String sendBatchTextMessage(String sendUserId,String content, String[] receiveUsers,Map<String, String> extras) throws RuntimeException{
		TextMessageBody textMessage = new TextMessageBody("users",receiveUsers,sendUserId,extras,content);
		Object result = chatService.sendMessage(textMessage);
		log.info(result.toString());
		if(result.toString().contains("error")){
			
			throw new RuntimeException("聊天发送失败");
		}
		
		return "ok";
	} 
	
	/**
	 * 发送透传消息
	 * @param action
	 * @param userId
	 * @param extras
	 * @return
	 * @throws Exception
	 */
	public static String sendInnerMessage(String sendUserId,String action, String receiveUserId,Map<String, String> extras) throws Exception{
		CommandMessageBody cmdMessage = new CommandMessageBody("users",new String[]{receiveUserId},sendUserId,extras,action);
		Object result = chatService.sendMessage(cmdMessage);
		log.info(result.toString());
		if(result.toString().contains("error")){
			throw new Exception("环信发送失败");
		}
		
		return "ok";
	} 
	
	/**
	 * 给群组发送透传信息
	 * @param sendUserId
	 * @param action
	 * @param groupId
	 * @param extras
	 * @return
	 * @throws Exception
	 */
	public static String sendInnerGroupMessage(String sendUserId,String action,String groupId,Map<String,String> extras) throws RuntimeException{
		CommandMessageBody cmdMessage = new CommandMessageBody("chatgroups",new String[]{groupId},sendUserId,extras,action);
		Object result = chatService.sendMessage(cmdMessage);
		log.info(result.toString());
		if(result.toString().contains("error")){
			throw new RuntimeException("环信发送失败");
		}
		return "ok";
	}
	
	/**
	 * 创建群组
	 * @param groupName
	 * @param userId
	 * @param members
	 * @throws RuntimeException
	 */
	public static String createGroup(String groupName,String userId,String[] members) throws RuntimeException{
		ChatGroupBody chatGroupBody = new ChatGroupBody(groupName, "server create group", true, GROUP_MAX_USER, false, userId, members);
		ResponseWrapper result = (ResponseWrapper)chatGroup.createChatGroup(chatGroupBody);
		log.info(result.toString());
		if(result.toString().contains("error")||StringUtils.isNullOrEmpty(result)){
			throw new RuntimeException("创建群组失败");
		}else{
			JSONObject obj = JSONObject.fromObject(result.getResponseBody().toString());
			return obj.getJSONObject("data").get("groupid").toString();
		}
	}
	
	/**
	 * 群组里面添加成员
	 * @param groupId
	 * @param userId
	 * @throws RuntimeException
	 */
	public static void addMemberToGroup(String groupId,String[] users) throws RuntimeException{
		UserNamesBody userNamesBody = new UserNamesBody(users);
		Object result = chatGroup.addBatchUsersToChatGroup(groupId, userNamesBody);
		log.info(result.toString());
		if(result.toString().contains("error")){
			throw new RuntimeException("添加成员失败");
		}
	}
	
	public static JSONArray getGroupMember(String groupId){
		ResponseWrapper result = (ResponseWrapper)chatGroup.getChatGroupUsers(groupId);
		JSONObject obj = JSONObject.fromObject(result.getResponseBody().toString());
		return obj.getJSONArray("data");
	}
	
	/**
	 * 群组里面删除成员
	 * @param groupId
	 * @param userId
	 * @throws RuntimeException
	 */
	public static void deleteMemberToGroup(String groupId,String[] users) throws RuntimeException{
		Object result = chatGroup.removeBatchUsersFromChatGroup(groupId, users);
		if(result.toString().contains("error")){
			throw new RuntimeException("删除成员失败");
		}
	}
	
	/**
	 * 删除群组
	 * @param groupId
	 * @throws RuntimeException
	 */
	public static void deleteGroup(String groupId) throws RuntimeException{
		Object result = chatGroup.deleteChatGroup(groupId);
		if(!result.toString().contains("success")){
			throw new RuntimeException("删除群组失败");
		}
	}
	
	
	private static String TITLE = "平安保险";
	private static String CONTENT = "【圣诞老人？我们还请来了财神爷！】";
	private static String imgUrl = "group1/M00/00/01/CgrI5lhbWR6ANDJdAAMcLqA2sxQ237.png";
	private static String linkUrl = "http://clouderp.combinedpay.cn:20080/web/scaleplate/161241.html";

	public static void main(String[] args) throws Exception {
//		String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//		JSONObject obj = new JSONObject();
//		obj.put("title", CONTENT);
//		obj.put("imgUrl",imgUrl);
//		obj.put("summary","");
//		obj.put("linkUrl",linkUrl);
//		obj.put("date", date);
//		Map<String, String> parameter = new HashMap<>();
//		parameter.put("action", "ad");
//		parameter.put("type", "image_and_text");
//		parameter.put("data", obj.toString());
//		
//		System.out.println(parameter.toString());
		Emchat.sendTextMessage("-1",CONTENT , "3143", null);

	}
	
}
